<template>
  <div class="blind-box-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>盲盒列表</span>
          <div>
            <el-button type="primary" @click="handleCreate">创建盲盒</el-button>
            <el-button type="success" @click="handleViewAllRecords" style="margin-left: 10px;">抽奖记录</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="盲盒名称">
          <el-input v-model="searchForm.name" placeholder="请输入盲盒名称" clearable @clear="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="封面图" width="100">
          <template #default="scope">
            <el-image 
              :src="scope.row.image" 
              fit="cover"
              style="width: 60px; height: 60px;"
              :preview-src-list="[scope.row.image]"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="盲盒名称" min-width="150" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="库存" width="120">
          <template #default="scope">
            <span v-if="scope.row.stock === -1">无限</span>
            <span v-else>{{ scope.row.stock - scope.row.sold }}/{{ scope.row.stock }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sold" label="已售" width="80" />
        <el-table-column label="奖品数" width="100">
          <template #default="scope">
            {{ scope.row.prize_count }}个
            <span v-if="scope.row.active_prize_count > 0" style="color: #67c23a;">
              ({{ scope.row.active_prize_count }}启用)
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" @click="handleViewRecords(scope.row)">记录</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 抽奖记录对话框 -->
    <el-dialog v-model="recordsDialogVisible" title="抽奖记录" width="80%">
      <el-table :data="recordsData" border stripe>
        <el-table-column prop="id" label="记录ID" width="80" />
        <el-table-column prop="customer_name" label="用户" width="120" />
        <el-table-column prop="telephone" label="手机号" width="120" />
        <el-table-column label="奖品图片" width="100">
          <template #default="scope">
            <el-image 
              :src="scope.row.prize_image" 
              fit="cover"
              style="width: 50px; height: 50px;"
            />
          </template>
        </el-table-column>
        <el-table-column prop="prize_name" label="奖品名称" min-width="150" />
        <el-table-column prop="prize_level" label="等级" width="80" />
        <el-table-column label="是否发放" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_delivered === 1 ? 'success' : 'warning'">
              {{ scope.row.is_delivered === 1 ? '已发放' : '未发放' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="抽取时间" width="180" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button 
              v-if="scope.row.is_delivered === 0"
              size="small" 
              type="primary"
              @click="handleDeliver(scope.row)"
            >
              发放
            </el-button>
            <span v-else style="color: #67c23a;">已发放</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const VITE_URL = (window as any).VITE_URL
const router = useRouter()

const loading = ref(false)
const tableData = ref([])
const searchForm = ref({
  name: '',
  status: ''
})

const recordsDialogVisible = ref(false)
const recordsData = ref([])
const currentBlindBoxId = ref(0)

// 获取盲盒列表
const getList = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams()
    if (searchForm.value.name) {
      params.append('name', searchForm.value.name)
    }
    if (searchForm.value.status !== '') {
      params.append('status', searchForm.value.status.toString())
    }

    const url = `${VITE_URL}/admin.blindBox/get_list?${params.toString()}`
    const res = await axios.get(url)
    tableData.value = res.data
  } catch (error) {
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  getList()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    name: '',
    status: ''
  }
  getList()
}

// 创建盲盒
const handleCreate = () => {
  router.push('/main/blindbox/edit')
}

// 编辑盲盒
const handleEdit = (row: any) => {
  router.push(`/main/blindbox/edit?blind_box_id=${row.id}`)
}

// 切换状态
const handleToggleStatus = async (row: any) => {
  const action = row.status === 1 ? 'offSale' : 'onSale'
  const actionText = row.status === 1 ? '下架' : '上架'
  
  try {
    await ElMessageBox.confirm(`确定要${actionText}该盲盒吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const url = `${VITE_URL}/admin.blindBox/${action}`
    const formData = new FormData()
    formData.append('ids[]', row.id.toString())

    const res = await axios.post(url, formData)
    if (res.data.status === 0) {
      ElMessage.success(`${actionText}成功`)
      getList()
    } else {
      ElMessage.error(res.data.message || `${actionText}失败`)
    }
  } catch (error) {
    // 用户取消
  }
}

// 删除盲盒
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该盲盒吗？删除后可在回收站恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const url = `${VITE_URL}/admin.blindBox/remove`
    const formData = new FormData()
    formData.append('ids[]', row.id.toString())

    const res = await axios.post(url, formData)
    if (res.data.status === 0) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(res.data.message || '删除失败')
    }
  } catch (error) {
    // 用户取消
  }
}

// 查看抽奖记录
const handleViewRecords = async (row: any) => {
  currentBlindBoxId.value = row.id
  recordsDialogVisible.value = true
  
  try {
    const url = `${VITE_URL}/admin.blindBox/get_records?blind_box_id=${row.id}`
    const res = await axios.get(url)
    recordsData.value = res.data
  } catch (error) {
    ElMessage.error('获取记录失败')
  }
}

// 发放奖品
const handleDeliver = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要发放该奖品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const url = `${VITE_URL}/admin.blindBox/deliver_prize`
    const formData = new FormData()
    formData.append('record_id', row.id.toString())

    const res = await axios.post(url, formData)
    if (res.data.status === 0) {
      ElMessage.success('发放成功')
      handleViewRecords({ id: currentBlindBoxId.value })
    } else {
      ElMessage.error(res.data.message || '发放失败')
    }
  } catch (error) {
    // 用户取消
  }
}

// 查看所有抽奖记录
const handleViewAllRecords = () => {
  router.push('/main/blindbox/records')
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.blind-box-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}
</style>
